package com.example.rbacmanage.controller;

import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.exception.MyException;
import com.example.rbacmanage.property.CodegenProperty;
import com.example.rbacmanage.service.CodegenService;
import com.example.rbacmanage.service.GenConfigService;
import com.example.rbacmanage.vo.CodegenPreviewVO;
import com.example.rbacmanage.vo.GenConfigForm;
import com.example.rbacmanage.vo.TablePageQuery;
import com.example.rbacmanage.vo.TablePageVO;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 代码生成器控制层
 *
 * @author Ray
 * @since 2.10.0
 */
@RestController
@RequestMapping("/codegen")
@Slf4j
public class CodegenController {
    @Autowired
    private CodegenService codegenService;
    @Autowired
    private GenConfigService genConfigService;
    @Autowired
    private CodegenProperty codegenProperties;
    //获取数据表分页列表
    @GetMapping("/table/page")
    public Result getTablePage(TablePageQuery queryParams) {
        PageInfo<TablePageVO> result = codegenService.getTablePage(queryParams);
        return Result.success(result);
    }

    /**
     * 获取代码生成配置
     */
    @GetMapping("/{tableName}/config")
    public Result<GenConfigForm> getGenConfigFormData(@PathVariable(value = "tableName") String tableName) {
        GenConfigForm formData = genConfigService.getGenConfigFormData(tableName);
        return Result.success(formData);
    }

    //保存代码生成配置
    @PostMapping("/{tableName}/config")
    public Result<?> saveGenConfig(@RequestBody GenConfigForm formData) throws MyException {
        genConfigService.saveGenConfig(formData);
        return Result.success();
    }

    //删除代码生成配置
    @DeleteMapping("/{tableName}/config")
    public Result<?> deleteGenConfig(@PathVariable(value = "tableName")  String tableName) {
        genConfigService.deleteGenConfig(tableName);
        return Result.success();
    }

    //获取预览生成代码
    @GetMapping("/{tableName}/preview")
    public Result<List<CodegenPreviewVO>> getTablePreviewData(@PathVariable(value = "tableName")  String tableName) throws MyException {
        List<CodegenPreviewVO> list = codegenService.getCodegenPreviewData(tableName);
        return Result.success(list);
    }

    //下载代码
    @GetMapping("/{tableName}/download")
    public void downloadZip(HttpServletResponse response, @PathVariable(value = "tableName")  String tableName) throws MyException {
        String[] tableNames = tableName.split(",");
        byte[] data = codegenService.downloadCode(tableNames);
        String downloadFileName = codegenProperties.getDownloadFileName() + "_" + System.currentTimeMillis() + ".zip";
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8));
        response.setContentType("application/octet-stream; charset=UTF-8");

        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            log.error("Error while writing the zip file to response", e);
            throw new RuntimeException("Failed to write the zip file to response", e);
        }
    }
}
